from django.http import JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from life_style.models import Lifestyle
from . import models
from .models import Usermodel


# Create your views here.
# 实现用户注册功能
def register(request):
    item = {}
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        re_pw = request.POST.get('re_password')
        email = request.POST.get('email')
        msg = ''
        # 检查必填字段是否为空
        if not all([username, password, re_pw, email]):
            msg = '所有字段均为必填项'
        # 检查两次密码是否一致
        elif password != re_pw:
            msg = '两次输入的密码不一致'
        # 验证邮箱是否已被注册（用户名由唯一约束保证）
        elif models.Usermodel.objects.filter(email=email).exists():
            msg = '该邮箱已被注册'
        # 创建用户并处理异常
        else:
            try:
                models.Usermodel.objects.create(name=username, pw=password, email=email)
                return redirect('login')
            except Exception as e:
                # 可以根据具体异常做更细致的提示，例如唯一约束冲突等
                if 'UNIQUE constraint failed' in str(e):
                    msg = '用户名或邮箱已存在'
                else:
                    msg = '创建用户时发生错误: {}'.format(str(e))
        item['error_msg'] = msg
    return render(request, 'register.html', item)

# 用户登录
def login(request):
    item = {}
    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')
        msg = ''
        if not all([email, password]):
            msg = '所有字段均为必填项'
        else:
            try:
                user_info = models.Usermodel.objects.filter(email=email, pw=password).first()
                if user_info:
                    item['username']=user_info.name
                    item['email']=user_info.email
                    request.session['user_info'] = item
                    return redirect('home')
                else:
                    msg = '密码错误'
            except models.Usermodel.DoesNotExist:
                msg = '用户不存在'
        item['error_msg'] = msg
    return render(request, 'login.html', item)
# 用户个人中心
def user_center(request):
    user_info = request.session.get('user_info', None)
    context = {}
    if user_info:
        email = user_info['email']
        try:
            user = models.Usermodel.objects.get(email=email)
            from life_style.models import Lifestyle,UserBehavior
            all_blog_count = Lifestyle.objects.filter(user=user).count()
            all_blog_comment = UserBehavior.objects.filter(user=user, action=5).count()
            all_blog_thumbUp = UserBehavior.objects.filter(user=user, action=1).count()
            all_blog = Lifestyle.objects.filter(user=user).order_by('-create_time')

            # 分页处理
            page = request.GET.get('page', 1)
            paginator = Paginator(all_blog, 6)

            try:
                blogs = paginator.page(page)
            except PageNotAnInteger:
                blogs = paginator.page(1)
            except EmptyPage:
                blogs = paginator.page(paginator.num_pages)

            user_head = user.user_head
            context['user_head'] = user_head
            context['all_blog_count'] = all_blog_count
            context['all_blog_comment'] = all_blog_comment
            context['all_blog_thumbUp'] = all_blog_thumbUp
            context['all_blog'] = all_blog
            context['blogs'] = blogs
            # 在视图中
            # 假设 user 是当前登录的用户对象
            # print(all_blog.category.get_wz_class_choices_display())

            context.update({
                'name': user.name,
                'email': user.email,
                'age': user.age,
                'gender': user.gender,
                'phone_num': user.phone_num,
                'address': user.address,
                'register_time': user.create_time.strftime('%Y-%m-%d %H:%M:%S'),  # 假设字段名为 create_time,
            })
        except models.Usermodel.DoesNotExist:
            return redirect('login')
    else:
        return redirect('login')
    return render(request, 'user_center.html', context)

# 用户信息修改
def user_edit(request):
    item = {}
    user_info = request.session.get('user_info', None)
    if user_info:
        email = user_info['email']
        user = models.Usermodel.objects.filter(email=email).first()
        if user:
            # 将用户信息添加到 item 中，用于传入模板
            item.update({
                'name': user.name,
                'email': user.email,
                'age': user.age,
                'user_head': user.user_head,
                'gender': user.gender,
                'phone_num': user.phone_num,
                'address': user.address,
            })
            if request.method == 'POST':
                # 更新逻辑
                username = request.POST.get('name',None)
                age = request.POST.get('age',None)
                gender = request.POST.get('gender',None)
                phone_num = request.POST.get('phone_num',None)
                address = request.POST.get('address',None)
                user_head_new = request.FILES.get('user_head',None)
                if user_head_new:
                    file_name = user_head_new.name
                    file_suffix = file_name.split('.')[-1]
                    file_list = ['png', 'jpg', 'jpeg']
                    if file_suffix in file_list:
                        # 构造新文件名：邮箱前缀 + 原始后缀
                        email_prefix = email.split("@")[0]
                        new_file_name = f"{email_prefix}.{file_suffix}"
                        # 暂时保存文件
                        user.user_head.save(new_file_name, user_head_new, save=False)

                # 更新用户信息
                user.name = username if username else user.name
                user.age = age if age else user.age
                user.gender = gender if gender else user.gender
                user.phone_num = phone_num if phone_num else user.phone_num
                user.address = address if address else user.address
                try:
                    user.save()
                    return redirect('person')
                except Exception as e:
                    item['error_msg'] = '保存时发生错误: {}'.format(str(e))
        else:
            item['error_msg'] = '用户不存在'
    else:
        item['error_msg'] = '请先登录'
    return render(request, 'user_edit.html', item)

def logout(request):
    # 清除 session 中的所有数据
    request.session.flush()
    # 重定向到登录页面或首页
    return redirect('login')  # 假设 'login' 是你的登录页面路由名称

def coll(request):
    user_info = request.session.get('user_info', None)
    if user_info is not None:
        email = user_info['email']
        user = models.Usermodel.objects.filter(email=email).first()
        user_head = user.user_head if user.user_head else ''
        coll_blogs = user.user_action.filter(action=2)
        context = {}
        context['coll_blogs'] = coll_blogs
        context['user_head'] = user_head
        return render(request,'favorites.html',context)
    return redirect('login')

# 用户浏览记录
def view_history(request):
    user_info = request.session.get('user_info', None)
    if user_info is not None:
        email = user_info['email']
        # query_set
        user = models.Usermodel.objects.filter(email=email).first()
        user_head = user.user_head if user.user_head else ""
        view_historys = user.user_action.filter(action=3).order_by('-create_time')

        # 对用户看过的博客进行驱动
        his_list = []  # 存储去重后的 博客对象
        tmp_ids = []  # 已经存入了his_list 的 博客 id
        for history in view_historys:
            if history.article.id not in tmp_ids:
                his_list.append(history)
                tmp_ids.append(history.article.id)

        context = {}
        context['view_historys'] = his_list
        context['user_head'] = user_head
        return render(request,'history.html',context)
# nohup python manage.py   __ qwe
# docker 容器化的部署方式 k8s

# docker run qwe

def del_action(request, ac_id):
    # 取消收藏  + 删除浏览历史
    referer = request.META.get('HTTP_REFERER')  # 获取当前请求的上一个请求地址
    # print(referer)
    user_info = request.session.get('user_info', None)
    if user_info is not None:
        email = user_info['email']
        user = models.Usermodel.objects.filter(email=email).first()

        # blog = Blog.objects.filter(id=blog_id).first()
        # 删除对应的收藏记录
        # user.user_action.filter(action_type=3, blog=blog).delete()
        user.user_action.filter(id=ac_id).delete()
        return redirect(referer)
    return redirect('login')

def author_profile(request, author_id):
    author = get_object_or_404(Usermodel, id=author_id)
    blogs = Lifestyle.objects.filter(user=author).order_by('-create_time')

    return render(request, 'author_profile.html', {
        'author': author,
        'blogs': blogs
    })